<?php

namespace Database\Seeders;

use App\Models\Address;
use Illuminate\Database\Seeder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Builder;

class OrderAddress extends Seeder
{
	public function run()
	{
		Address::query()
			->where(function (Builder $query) {
				$query->where('id_code', 'like', "%src%")
					->orWhere('id_name', 'like', "%src%")
					->orWhere('contact_name', 'like', "%src%")
					->orWhere('address', 'like', "%src%");
			})->chunks(20, function (Collection $addresses) {
				
				if ($addresses->isEmpty()) return false;
				
				/**
				 * @var Address $address
				 */
				foreach ($addresses as $address) {
				
					$address->id_code = strip_tags(clean($address->id_code, 'default'));
					$address->id_name = strip_tags(clean($address->id_name, 'default'));
					$address->contact_name = strip_tags(clean($address->contact_name, 'default'));
					$address->address = strip_tags(clean($address->address, 'default'));
					$address->save();
					
					Log::info("===== User: {$address->user_id}");
					
					$orders = $address->user->orders;
					
					if ($orders->isEmpty()) continue;
					
					foreach ($orders as $order) {
						$addr = $order->address;
						if (count($addr) > 0) {
							$order->address = [
								'address' => strip_tags(clean($addr['address'], 'default')),
								'contact_name' => strip_tags(clean($addr['contact_name'], 'default')),
								'contact_phone' => $addr['contact_phone'],
							];
							$order->save();
							$order->items()->update(['delivery_data' => null]);
							
							Log::info("===== Order: {$order->id}");
						}
					}
				}
				
				return true;
				
			});
	}
}
